package com.xbniao.owms.utils;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;

import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;


public class FileUtil {
	/**
	 * 
	  * @param InputPath          原图地址
	  * @param OutputPath       修改后
	  * @param OutputWidth    修改宽度
	  * @param OutputHeight   修改高度
	  * @return
	 */
	public static boolean stretchImg(String InputPath,String OutputPath,int OutputWidth,int OutputHeight)throws Exception {
		// 建立输出文件对象
		File file = new File(OutputPath);
		FileOutputStream tempout = new FileOutputStream(file);
		Toolkit tk = Toolkit.getDefaultToolkit();
		Image img = tk.getImage(InputPath);
		Applet app = new Applet();
		MediaTracker mt = new MediaTracker(app);
		mt.addImage(img, 0);
		mt.waitForID(0);
		if (img.getWidth(null) == -1) {
			return false;
		} else {
			BufferedImage buffImg = new BufferedImage(OutputWidth, OutputHeight,BufferedImage.TYPE_INT_RGB);
			Graphics g = buffImg.createGraphics();
			g.setColor(Color.white);
			g.fillRect(0, 0, OutputWidth, OutputHeight);
			g.drawImage(img, 0, 0, OutputWidth, OutputHeight, null);
			g.dispose();
			ImageIO.write(buffImg, "JPG", tempout);
			tempout.close();
		}
		return true;
	}

	/**
     * 生成缩略图
     * @param inputFile        需要生成缩略图的PDF路径
     * @param outputFile      生成缩略图的放置路径
     */
    @SuppressWarnings("rawtypes")
	public static boolean pdfToImg(String inputFile, String outputFile) throws Exception{
            float rotation = 0f;
            //缩略图显示倍数，1表示不缩放，0.5表示缩小到50%
            float zoom = 1f;
            Document document = new Document();
            document.setFile(inputFile);
            BufferedImage image = (BufferedImage)document.getPageImage(0, GraphicsRenderingHints.SCREEN,Page.BOUNDARY_CROPBOX, rotation, zoom);
            
            Iterator iter = ImageIO.getImageWritersBySuffix("jpg");
            ImageWriter writer = (ImageWriter)iter.next();
            
            FileOutputStream out = new FileOutputStream(new File(outputFile));
            ImageOutputStream outImage = ImageIO.createImageOutputStream(out);
            
            writer.setOutput(outImage);
            writer.write(new IIOImage(image, null, null));
        
        return true;
    }

	public static void main(String[] a) throws Exception {
		// s_pic(大图片路径,生成小图片路径,大图片文件名,生成小图片文名,生成小图片宽度,生成小图片高度)
//		System.out.println(FileUtil.stretchPic("H:/ceshi.jpg", "H:/111.jpg", 120, 80));
		FileUtil.pdfToImg("H:/ceshi.pdf", "H:/222.jpg");
	}

}
